package com.qxzn.module.agora;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.util.PermissionUtil;
import com.qxzn.app.util.ActivityStack;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.app.util.SystemUtil;
import com.tbruyelle.rxpermissions2.Permission;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 视频监控
 */
public class VideoMonitoringActivity extends BaseActivity {

    @BindView(R2.id.ll_user)
    LinearLayout llUser;
    @BindView(R2.id.iv_head)
    ImageView ivHead;
    @BindView(R2.id.tv_user)
    TextView tvUser;
    @BindView(R2.id.tv_status)
    TextView tvStatus;
    @BindView(R2.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R2.id.iv_hungup)
    ImageView ivHungup;
    @BindView(R2.id.cb_mute)
    CheckBox cbMute;
    @BindView(R2.id.ll_mute)
    LinearLayout llMute;
    @BindView(R2.id.ll_turn_left)
    LinearLayout llTurnLeft;
    @BindView(R2.id.tv_hungup)
    TextView tvHungup;
    @BindView(R2.id.ll_turn_right)
    LinearLayout llTurnRight;

    private LinearLayout.LayoutParams fullParams;
    private LinearLayout.LayoutParams middleParams;
    private boolean isBig;
    private PermissionUtil util;
    private boolean needRequestPermission = true;

    @Override
    protected int initLayout() {
        return R.layout.activity_video_monitoring;
    }

    @Override
    protected void initView() {
        fullParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SystemUtil.getScreenHeight(this));
        middleParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (SystemUtil.getScreenHeight(this) - SystemUtil.getStatusBarHeight(this)) / 2);
    }

    @Override
    protected void iniTitleBar() {
        title_bar.setVisibility(View.GONE);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    protected void setFullScreen() {
        super.setFullScreen();

    }

    private void initListener() {
        AgoraManager.getInstance().setOnUserStatusChangeListener(new AgoraManager.OnUserStatusChangeListener() {
            @Override
            public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
//                SystemUtil.setMediaVolume(VideoChatCallActivity.this, currentVolume);//恢复被声网修改的音量
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AgoraManager.getInstance().setupLocalVideo(getApplicationContext()).startPreview();
                        llUser.addView(AgoraManager.getInstance().getLocalSurfaceView(), fullParams);
                        AgoraManager.getInstance().getUserCurrentRow().put(AgoraManager.mLocalUid, 1);
                    }
                });
            }

            @Override
            public void onFirstRemoteVideoDecoded(int uid, int width, int height, int elapsed) {

            }

            @Override
            public void onUserJoined(final int uid, int elapsed) {
                AppUtil.showLog("agpra video user join = " + uid);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        rlHead.setVisibility(View.INVISIBLE);
                        llMute.setVisibility(View.VISIBLE);
                        llTurnLeft.setVisibility(View.VISIBLE);
                        llTurnRight.setVisibility(View.VISIBLE);
                        tvHungup.setText("挂断");
                        llUser.getChildAt(0).setLayoutParams(middleParams);
                        AgoraManager.getInstance().setupRemoteVideo(getApplicationContext(), uid).startPreview();
                        llUser.addView(AgoraManager.getInstance().getSurfaceView(uid), AgoraManager.getInstance().getUserMap().size() - 1, middleParams);
                    }
                });
            }

            @Override
            public void onUserOffline(final int uid, int reason) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!isFinishing()) {
                            //移除已离开用户
                            llUser.removeView(AgoraManager.getInstance().getSurfaceView(uid));
                        }
                        //清除缓存的SurfaceView
                        AgoraManager.getInstance().removeSurfaceView(uid);

                        if (AgoraManager.getInstance().getUserMap().size() <= 1) {
                            Toast.makeText(VideoMonitoringActivity.this, "对方已经挂断电话", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }
                });
            }

            @Override
            public void onSurfaceItemClick(int uid) {
                if (isBig) {
                    AgoraManager.getInstance().getSurfaceView(uid).setLayoutParams(middleParams);
                } else {
                    AgoraManager.getInstance().getSurfaceView(uid).setLayoutParams(fullParams);
                }
                isBig = !isBig;
            }
        });

        cbMute.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (buttonView.isPressed()) {
                    if (isChecked) {
                        AgoraManager.getInstance().silence(true);
                    } else {
                        AgoraManager.getInstance().silence(false);
                    }
                }
            }
        });
    }

    private void joinToRoom() {
        requestVideoChat(2);
        AgoraManager.getInstance().joinChannel(SharePreferenceUtil.getDeviceId(this));
    }

    private void requestVideoChat(int code) {
        JSONObject params = new JSONObject();
        params.put("sender", SharePreferenceUtil.getUserName(this));//发送者，桌面版：sender为机器码，APP：sender为手机号
        params.put("number", SharePreferenceUtil.getDeviceId(this));//接收者的手机号
        params.put("code", code);//0电话通话 1视频通话 2监控 3聊天 101 用户绑定机器人请求授权
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(params));
        Call<BaseBean> call = HttpRequest.getService().requestVideoChat(body);
        call.enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                BaseBean bean = response.body();
                if (bean != null && bean.getCode() == 200) {
                    AppUtil.showLog("call video communication success");
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                AppUtil.showToast(VideoMonitoringActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

    /**
     * 动态权限请求k
     */
    private void requestPermission() {
        util = PermissionUtil.getInstant().setActivity(this).requestPermission(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {
                AppUtil.showLog("RegisterFace3Activity.accept");
                if (permission.granted) {
                    initVideoCall();
                } else if (permission.shouldShowRequestPermissionRationale) {
                    requestPermission();
                } else {
                    util.showPermissionNeedDialog(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            needRequestPermission = true;
                            AppUtil.showLog("RegisterFace3Activity.setConfirmClick");
                            // 设置你的操作事项
                            CommonUtil.gotoAppDetailIntent(VideoMonitoringActivity.this);
                            dialog.dismiss();
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            needRequestPermission = false;
                            AppUtil.showLog("AutoLoginActivity.setCancelClick");
                            dialog.dismiss();
                        }
                    }, PermissionUtil.READ_EXTERNAL_STORAGE, PermissionUtil.WRITE_EXTERNAL_STORAGE, PermissionUtil.CAMERA, PermissionUtil.RECORD_AUDIO);
                }
            }
        }, null, PermissionUtil.READ_EXTERNAL_STORAGE, PermissionUtil.WRITE_EXTERNAL_STORAGE, PermissionUtil.CAMERA, PermissionUtil.RECORD_AUDIO);
    }

    private void initVideoCall() {
        AgoraManager.getInstance().init(this);
        initListener();
        joinToRoom();
    }

    @OnClick(R2.id.iv_hungup)
    public void onViewClicked() {
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        AgoraManager.getInstance().stopPreview();
        AgoraManager.getInstance().leaveChannel();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (needRequestPermission) {
            needRequestPermission = false;
            requestPermission();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityStack.removeActivity(this);
        AgoraManager.getInstance().destroy();
        AgoraManager.getInstance().getUserMap().clear();
        AgoraManager.getInstance().getUserCurrentRow().clear();
        AgoraManager.getInstance().setOnUserStatusChangeListener(null);
    }

    @OnClick({R2.id.iv_hungup, R2.id.iv_turn_left, R2.id.iv_turn_right})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.iv_hungup) {
            finish();
        } else if (i == R.id.iv_turn_left) {
            requestVideoChat(201);
        } else if (i == R.id.iv_turn_right) {
            requestVideoChat(202);
        }
    }
}
